package top.laoshuzi.common.mvp.presenter;


import android.support.annotation.Nullable;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import top.laoshuzi.common.mvp.annotations.BindRouterPresenter;
import top.laoshuzi.common.mvp.annotations.RouterPresenter;
import top.laoshuzi.common.mvp.factory.PresenterFactory;
import top.laoshuzi.common.mvp.view.View;

public class RouterPresenterFactory implements PresenterFactory {

    private Object object;
    private List<Field> presenterFields;

    @Nullable
    public static RouterPresenterFactory fromViewClass(Object viewObject) {

        if (viewObject.getClass().isAnnotationPresent(RouterPresenter.class)) {
            List<Field> fields = new ArrayList<>();
            Class tempClass = viewObject.getClass();
            while (tempClass != null && View.class.isAssignableFrom(tempClass)) {
                for (Field field : tempClass.getDeclaredFields()) {
                    if (field.isAnnotationPresent(BindRouterPresenter.class)) {
                        fields.add(field);
                    }
                }
                tempClass = tempClass.getSuperclass();
            }
            return new RouterPresenterFactory(viewObject, fields);
        }
        return null;
    }

    private RouterPresenterFactory(Object object, List<Field> presenterFields) {
        this.object = object;
        this.presenterFields = presenterFields;
    }

    @Override
    public List<? extends Presenter> createPresenter() {

        List<Presenter> presenters = new ArrayList<>();

        try {
            for (Field field : presenterFields) {
                field.setAccessible(true);
                if (Presenter.class.isAssignableFrom(field.get(object).getClass())) {
                    presenters.add((Presenter) field.get(object));
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return presenters;
    }

    @Override
    public void bindPresenter(List<? extends Presenter> presenters) {

    }
}
